package cn.dev.mybatis.core;

import cn.dev.mybatis.exception.MybatisException;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class SqlSessionFactory {
    private DataSource dataSource;

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public SqlSession openSession() {
        return openSession(true);
    }

    public SqlSession openSession(boolean autoCommit) {
        try {
            if (dataSource == null) {
                throw new MybatisException("dataSource property is required");
            }
            return openSession(dataSource.getConnection(), autoCommit);
        } catch (SQLException e) {
            throw new MybatisException(e);
        }
    }

    public SqlSession openSession(Connection connection) {
        return openSession(connection, true);
    }

    public SqlSession openSession(Connection connection, boolean autoCommit) {
        return new SqlSession(connection, autoCommit);
    }
}
